package com.dream.dynamic_datasource.aop;

import com.dream.dynamic_datasource.entity.user.User;
import com.dream.dynamic_datasource.ServiceForChangeDb.DBChangeService;
import com.dream.dynamic_datasource.utils.JwtUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @description: 日志切面
 * @author: Luo
 * @create: 2020-07-14 15:45
 */
@Aspect
@Component
@Order(-1)
public class DataSourceAop {
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private DBChangeService dbChangeService;
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    //切入点描述 这个是controller包的切入点
    @Pointcut("execution(public * com.dream.dynamic_datasource.service..*.*(..))")
    public void controllerLog(){}
    /**
     * 进入方法之前拦截
     * @param point
     * @date 2020/7/14 15:48
     */
    @Before( "controllerLog()") //在切入点的方法run之前要干的
    public void logBeforeController(JoinPoint point) {
        User logUser = jwtUtil.getLogUser();
        try {
           if(logUser!=null){
               String dbName = logUser.getDbName();
               dbChangeService.changeDb(dbName);
           }
        } catch (Exception e) {
            e.printStackTrace();
        }



    }
    /**
     * 正常执行程序的返回值
     * @param joinPoint
     * @param returnOb
     * @date 2020/7/14 15:49
     */
    @AfterReturning(pointcut = "controllerLog()",returning = "returnOb") //在切入点的方法run之前要干的
    public void logAfterController(JoinPoint joinPoint,Object returnOb) {
        // 记录返回参数
        logger.info("################returnOb : " + returnOb);
    }
    /**
     * 执行程序出现异常
     * @param joinPoint
     * @param ex
     * @date 2020/7/14 15:49
     */
    @AfterThrowing(pointcut = "controllerLog()", throwing = "ex")
    public void doAfterThrowing(JoinPoint joinPoint, Exception ex) {

    }











}
